package com.yang;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

public class MusicService extends Service {

    private MediaPlayer mediaPlayer;

    private MyBinder myBinder;

    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        myBinder = new MyBinder();
        return myBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (myBinder != null) {
            myBinder = null;
        }
        return super.onUnbind(intent);
    }

    class MyBinder extends Binder {
        public void startPlay() {
            if (mediaPlayer == null) {
                mediaPlayer = MediaPlayer.create(MusicService.this, R.raw.music);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            }
            mediaPlayer.start();
        }

        public void pausePlay() {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        }

        public void continuePlay() {
            if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                mediaPlayer.start();
            }
        }

        public void stopPlay() {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }

        public int getProgress() {
            if (mediaPlayer != null) {
                return 100 * mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
            }
            return 0;
        }

        public void setProgressPosition(int progressPosition) {
            if (mediaPlayer != null) {
                mediaPlayer.seekTo(progressPosition * mediaPlayer.getDuration() / 100);
            }
        }
    }
}